package com.example.springboot.service;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.entity.User;
import com.example.springboot.excption.ServiceException;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.utils.TokenUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 功能:
 * 作者：jian
 * 日期：2024/3/14 15:28
 */
@Service
public class UserService extends ServiceImpl<UserMapper,User> {

    @Resource
    UserMapper userMapper;




    @Override
    public boolean save(User entity) {
        if (StrUtil.isBlank(entity.getName())){
            entity.setName(entity.getUsername());
        }
        if (StrUtil.isBlank(entity.getPassword())){
            entity.setPassword("123");
        }
        if (StrUtil.isBlank(entity.getRole())){
            entity.setRole("用户");
        }

        return super.save(entity);
    }

    public User selectByUsername(String username){
        //获取user对象的所有数据
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();


        queryWrapper.eq("username",username);  //eq==> == where username=#{username}
        return getOne(queryWrapper);
    }



//验证用户账户是否合法
    public User login(User user) {
        User dbUser = this.selectByUsername(user.getUsername());

//       User dbUser=  userMapper.selectByUsername(user.getUsername());
//        User dbUser =  userMapper.selectOne(queryWrapper);
       if (dbUser==null){
           //抛出一个自定义异常
           throw new ServiceException("账号不存在");
       }
       if (!user.getPassword().equals(dbUser.getPassword())){
           throw new ServiceException("用户名或密码错误");
       }
       //生成token
        String token = TokenUtils.createToken(dbUser.getId().toString(),dbUser.getPassword());
       dbUser.setToken(token);
        return  dbUser;
    }

    public User register(User user) {
//        User dbUser=  userMapper.selectByUsername(user.getUsername());
        User dbUser = selectByUsername(user.getUsername());
        if (dbUser!=null){
            //抛出一个自定义异常
            throw new ServiceException("用户名已存在");
        }
        user.setName("honey-"+ RandomUtil.randomNumbers(4));
        userMapper.insert(user);
        return user;
    }

    public void resetPassword(User user) {
//        User dbUser = userMapper.selectByUsername(user.getUsername());
        User dbUser = selectByUsername(user.getUsername());
        if (dbUser==null){
            //抛出一个自定义异常
            throw new ServiceException("用户名不存在");
        }
        if(!user.getPhone().equals(dbUser.getPhone())){
            throw new ServiceException("验证错误");
        }
        dbUser.setPassword("123"); //重置密码

       updateById(dbUser);


    }
}